﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using NPOI.HSSF.UserModel;
using NPOI.SS.Converter;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace HtmlShowExcel.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;

        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {

        }

        public ActionResult OnPostOpenExcel(string dir)
        {
            string excelHtml = "";
            try
            {
                excelHtml = ExcelToHtml(dir);
            }
            catch (Exception e)
            {
                excelHtml = "<div>" + e.Message + "</div>";
            }

            return Content(excelHtml, "text/html");
        }

        public ActionResult OnPostSend()
        {
            //var path = @"E:\Excel";
            //Dir2Json dir = new Dir2Json();
            //string result = dir.GetDir(path);

            //获取当前系统的根路径
            string rootpath = @"E:\zxf\网上公布的文件\各工程有关的共享文件";
#if DEBUG
            rootpath = @"E:\Excel\各工程有关的共享文件";
#endif

            var list = GetallDirectory(new List<FileNames>(), rootpath).ToArray();

            return new JsonResult(Newtonsoft.Json.JsonConvert.SerializeObject(list.ToList()));
        }

        public string ExcelToHtml(string fileName)
        {
            ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter();
            // 设置输出参数
            excelToHtmlConverter.OutputColumnHeaders = true;
            excelToHtmlConverter.OutputHiddenColumns = false;
            excelToHtmlConverter.OutputHiddenRows = false;
            excelToHtmlConverter.OutputLeadingSpacesAsNonBreaking = true;
            excelToHtmlConverter.OutputRowNumbers = true;
            excelToHtmlConverter.UseDivsToSpan = true;

            string extension = Path.GetExtension(fileName).ToUpper().Trim();
            if (extension == ".XLSX")
            {
                //XSSFWorkbook workbook = ExcelToHtmlUtils.
                var doc = ExcelToHtmlConverter.Process(fileName);
                return doc.InnerXml;
            }
            else
            {
                HSSFWorkbook workbook = ExcelToHtmlUtils.LoadXls(fileName);
                // 处理的Excel文件
                excelToHtmlConverter.ProcessWorkbook(workbook);
                //添加表格样式
                excelToHtmlConverter.Document.InnerXml =
                    excelToHtmlConverter.Document.InnerXml.Insert(
                        excelToHtmlConverter.Document.InnerXml.IndexOf("<head>", 0) + 6,
                        @"<style>table, td, th{border:1px solid green;}th{background-color:green;color:white;}</style>"
                    );

                //方法一
                return excelToHtmlConverter.Document.InnerXml;
            }
        }

        //获得指定路径下所有文件名
        public static List<FileNames> getFileName(List<FileNames> list, string filepath)
        {
            DirectoryInfo root = new DirectoryInfo(filepath);
            var files = root.GetFiles("*.xls?");
            if (files != null && files.Count() > 0)
            {
                foreach (FileInfo f in root.GetFiles("*.xls?"))
                {
                    if (f.Name.Length > 0 && f.Name[0] == '~') continue;

                    string extension = Path.GetExtension(f.FullName).ToUpper().Trim();
                    if (extension == ".XLS" || extension == ".XLSX")
                    {
                        list.Add(new FileNames
                        {
                            title = f.Name,
                            href = f.FullName
                        });
                    }
                }
            }
            return list;
        }
        //获得指定路径下的所有子目录名
        // <param name="list">文件列表</param>
        // <param name="path">文件夹路径</param>        
        public static List<FileNames> GetallDirectory(List<FileNames> list, string path)
        {
            DirectoryInfo root = new DirectoryInfo(path);
            var dirs = root.GetDirectories();
            if (dirs.Count() != 0)
            {
                foreach (DirectoryInfo d in dirs)
                {
                    if (d.GetFiles("*.xls?").Length > 0)
                    {
                        list.Add(new FileNames
                        {
                            title = d.Name,
                            children = GetallDirectory(new List<FileNames>(), d.FullName)
                        });
                    }
                }
            }
            list = getFileName(list, path);
            return list;
        }
    }

    public class FileNames
    {
        public string id { get; set; } = Guid.NewGuid().ToString();
        public string title { get; set; }
        public List<FileNames> children { get; set; }
        public string href { get; set; }
    }
    public class state
    {
        public bool opened { get; set; }
    }



    //public class Dir2Json
    //{
    //    private List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();

    //    public string GetDir(string path)
    //    {
    //        DirectoryInfo folder = new DirectoryInfo(path);
    //        DirectoryInfo[] dirs = folder.GetDirectories("", SearchOption.AllDirectories);
    //        foreach (var item in dirs)
    //        {
    //            var d = new Dictionary<string, object>();
    //            d.Add("id", Guid.NewGuid().ToString());
    //            if(item!=null)
    //            {
    //                d.Add("title", item.Name);
    //                string extension = Path.GetExtension(item.FullName).ToUpper().Trim();
    //                if (extension==".XLS" || extension == ".XLSX")
    //                {

    //                }
    //            }
    //            //d.Add("state", "closed");

    //            if (GetFileNames(item.FullName).Count > 0)
    //            {
    //                var f = new List<Dictionary<string, object>>();
    //                int cc = 11;
    //                foreach (var c in GetFileNames(item.FullName))
    //                {
    //                    cc++;
    //                    f.Add(new Dictionary<string, object>() { { "id", Guid.NewGuid().ToString() }, { "title", c }, { "url", item + "/" + c } });

    //                }
    //                d.Add("children", f);
    //            }
    //            list.Add(d);
    //        }
    //        return Newtonsoft.Json.JsonConvert.SerializeObject(list);
    //    }
    //    public List<string> GetFileNames(string path)
    //    {
    //        DirectoryInfo folder = new DirectoryInfo(path);
    //        List<string> files = new List<string>();
    //        foreach (FileInfo file in folder.GetFiles("*.html"))
    //        {
    //            if (file.Name.Contains("_"))
    //            {
    //                continue;
    //            }
    //            files.Add(file.Name);
    //        }
    //        return files;
    //    }
    //}
}
